'use strict';

angular.module('afasApp')
  .controller('DiscountTypesCtrl', ['$scope', 'Services', '$state', function ($scope, Services, $state) {

    $scope.items = [];
    $scope.params = {};

    // PAGINATION
    $scope.pagesize = 10;

    $scope.pagination = {
      current: 1
    };

    $scope.pageChanged = function(newPage) {
      getResultsPage(newPage);
    };

    function getResultsPage(pageNumber) {
      var data = $scope.params;
      data.pagesize = $scope.pagesize;
      data.page = (pageNumber - 1);
      $scope.pagination.current = pageNumber;
      Services.getItems('discount_types', data)
      .then(function( results ) {
        console.log(results.headers);
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.totalItems = pagingData.TotalCount;
        $scope.items = results.data;
      });
    }
    getResultsPage(1);


    // function applyRemoteData( newData ) {
    //   $scope.countries = newData;
    // }

    // function loadRemoteData() {
    //   Services.getItems('countries')
    //   .then(function( results ) {
    //     applyRemoteData( results.data );
    //   });
    // }

    // loadRemoteData();

    $scope.addCountry = function () {
      $scope.errors = {};
      Services.add('countries', $scope.countryNew)
      .then(function(){
        $scope.countryNew = {};
        $state.go( '^.list' );
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    };
  }])
  .controller('DiscountTypeCreateCtrl', ['$scope', 'Services', '$state', '$stateParams', function ($scope, Services, $state, $stateParams) {

    var date = new Date();
    date.setMinutes(0);
    date.setSeconds(0);

    $scope.item = {
      'DefaultValidFrom': date,
      'DefaultValidUntil': date
    };
    $scope.errors = {};

    $scope.add = function () {
      $scope.errors = {};
      Services.add('discount_types', $scope.item)
      .then(function(){
        $scope.item = {};
        $state.go( '^.list' );
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    };
  }])
  .controller('CountryCtrl', ['$scope', 'Services', '$state', '$stateParams', function ($scope, Services, $state, $stateParams) {

    $scope.country = {};
    $scope.currentID = $stateParams.id;

    Services.getItem('countries', $stateParams.id)
    .then(function(results){
      $scope.country = results.data;
    });

    $scope.updateCountry = function () {
      Services.update('countries', $scope.country, $scope.currentID)
      .then(function(){
        $state.go( '^' );
      });
    };
  }]);